package com.srwl.mytx.contrack;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ContactContrackImpl implements ContactContrack.Presenter {
    private static final String TAG = "ContactContrackImpl";

    private ContactContrack.View view;
    private Context context;

    public ContactContrackImpl(ContactContrack.View view, Context context) {
        this.view = view;
        this.context = context;
    }

    @Override
    public void addContact(Contact contact, String inviteMessage) {
        User targetUser = contact.getTargetUser();
        if (targetUser == null) {
            Log.e(TAG, "addContact: 联系人中没有用户信息" + contact.toString());
            return;
        }
        if (UserProfileManager.getInstance().getLoginUserInfo().getuId().equals(targetUser.getuId())) {
            view.showToast(context.getString(R.string.not_add_myself));
            return;
        }

        if (Helper.getInstance().isNormalContact(targetUser.getuId())) {
            view.showToast(context.getString(R.string.This_user_is_already_your_friend));
            return;
        }

        final Contact updateContact = new Contact();
        //设置我给对方的位置权限
        updateContact.setTLocation(contact.getTLocation());
        sendInviteMessage(updateContact, targetUser.getUId(), inviteMessage);

    }

    @Override
    public void start() {

    }

    private void sendInviteMessage(Contact updateContact, String uId, String inviteMessage) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
//        progressDialog = new ProgressDialog(AddContactActivity.this);
//        progressDialog.setContent(getResources().getString(R.string.Is_sending_a_request));
//        progressDialog.setCanceledOnTouchOutside(false);
//        progressDialog.show();

        if (TextUtils.isEmpty(inviteMessage)) {
            inviteMessage = context.getResources().getString(R.string.default_invite_message);
        }
        updateContact.setInviteMessage(inviteMessage);
        updateContact.settId(uId);

//        if (!TextUtils.isEmpty(cId)) {
//            updateContact.setcId(cId);
//        }
//        if (!TextUtils.isEmpty(tCid)) {
//            updateContact.settCid(tCid);
//        }
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        body.put("ct", updateContact);
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .sendInviteMessage(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        // progressDialog.dismiss();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            view.showToast(context.getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            switch (result.getStatus()) {

                                case Constant.REFUSE_ADD_CONTACT:
                                    view.showToast("对方已经拒绝您的添加联系人请求," + result.getData().toString() + "天后可再次添加");
                                    break;
                                case Constant.REFUSE_ADD_CONTACT_IS_HAVE:
                                    view.showToast("好友请求已经发起了,不能重新发起好友请求");
                                    break;
                                default:
                                    view.showToast("系統错误");
                            }
                            return;
                        }


                        if (result.getData() != null) {
                            JSONObject jsonObject = (JSONObject) result.getData();
                            Contact contact = jsonObject.toJavaObject(Contact.class);
                            //前端使用tid进行关联查询,所以将后端的mid设置给tid
                            //  contact.setmId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                            contact.settId(contact.getUser().getuId());
                            contact.setGroupName(updateContact.getGroupName());
                            DBManager.getInstance().getDaoSession().getContactDao().insertOrReplace(contact);
                            Helper.getInstance().refreshCache();
                            LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context);
                            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANGED));
                            view.showToast("你一直在对方的联系人中，添加联系人完成");
                        } else {
                            view.showToast(context.getString(R.string.send_invite_message_seccess));

                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        //  progressDialog.dismiss();
                        view.showToast(context.getString(R.string.system_busy));
                    }
                });
    }
}
